package com.im.filters;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class LogFilter implements Filter {

	PrintWriter logFile;
	
	@Override
	public void destroy() {
		
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		
		String ip = request.getLocalAddr();
		System.out.println(ip+" @ "+new Date());
		logFile.println(ip+" @ "+new Date());
		logFile.flush();
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		
		String fileName = config.getInitParameter("log-file");
		try {
			logFile = new PrintWriter(new File(fileName));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	

}
